<template>
  <div class="p-2 cgformErpList">
    <div class="content">
      <!--引用表格-->
      <BasicTable @register="registerTable" :rowSelection="rowSelection" @row-click="clickThenCheck" @selection-change="changeThenCheck">
        <!--插槽:table标题-->
        <template #tableTitle>
          <a-button type="primary" v-auth="'xcbd:xcbd_sales_contract:add'"  @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
          <a-button type="primary" v-auth="'xcbd:xcbd_sales_contract:exportXls'"  preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button type="primary" v-auth="'xcbd:xcbd_sales_contract:importExcel'"  preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
<!--          <a-dropdown v-if="selectedRowKeys.length > 0">
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="batchHandleDelete">
                  <Icon icon="ant-design:delete-outlined"></Icon>
                  删除
                </a-menu-item>
              </a-menu>
            </template>
            <a-button  v-auth="'xcbd:xcbd_sales_contract:deleteBatch'">批量操作
              <Icon icon="mdi:chevron-down"></Icon>
            </a-button>
          </a-dropdown>-->
          <!-- 高级查询 -->
          <super-query :config="superQueryConfig" @search="handleSuperQuery" />
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
        </template>
        <!--字段回显插槽-->
        <template v-slot:bodyCell="{ column, record, index, text }">
          <template v-if="column.dataIndex==='homeAddress'">
            <!--省市区字段回显插槽-->
            {{ getAreaTextByCode(text) }}
          </template>
          <template v-if="column.dataIndex==='contractDescription'">
            <!--富文本件字段回显插槽-->
            <div v-html="text"></div>
          </template>
          <template v-if="column.dataIndex==='attachment'">
            <!--文件字段回显插槽-->
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
            <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
          </template>
        </template>
      </BasicTable>
      <!--子表表格tab-->
      <a-tabs defaultActiveKey="1" style="margin: 10px">
        <a-tab-pane tab="收款记录" key="1" >
          <XcbdCollectionRecordList />
        </a-tab-pane>
        <a-tab-pane tab="工作流程" key="2" forceRender>
          <XcbdWorkflowList />
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- 表单区域 -->
    <XcbdSalesContractModal @register="registerModal" @success="handleSuccess"></XcbdSalesContractModal>
    <ViceGeneralManagerModal title="副总经理审批" @register="registerViceGeneralManagerModal" @success="handleSuccess"/>
    <GeneralManagerModal title="总经理审批" @register="registerGeneralManagerModal" @success="handleSuccess"/>
  </div>
</template>

<script lang="ts" name="xcbd-xcbdSalesContract" setup>
  import {ref, reactive, computed, unref,provide} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage'
  import {useModal} from '/@/components/Modal';
  import XcbdSalesContractModal from './components/XcbdSalesContractModal.vue'
  import { useUserStore } from '/@/store/modules/user';
  import XcbdCollectionRecordList from './XcbdCollectionRecordList.vue'
  import XcbdWorkflowList from './XcbdWorkflowList.vue'
  import {columns, searchFormSchema, superQuerySchema} from './XcbdSalesContract.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl} from './XcbdSalesContract.api';
  import {downloadFile} from '/@/utils/common/renderUtils';
  import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
  import GeneralManagerModal from '@/views/qperationsAssistant/contract/generalManager/components/XcbdWorkflowModal.vue';
  import ViceGeneralManagerModal from '@/views/qperationsAssistant/contract/viceGeneralManager/components/XcbdWorkflowModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import {mapTableTotalSummary} from "@/utils/common/compUtils";
  const { hasPermission } = usePermission();
  const queryParam = reactive<any>({});
  //注册model
  const [registerModal, {openModal}] = useModal();
  const [registerViceGeneralManagerModal, { openModal: openViceGeneralManagerModal }] = useModal();
  const [registerGeneralManagerModal, { openModal: openGeneralManagerModal }] = useModal();
   //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '销售合同',
           api: list,
           columns,
           canResize: false,
           clickToRowSelect: true,
           rowSelection: {type: 'checkbox' }, //默认是 checkbox 多选，可以设置成 radio 单选
           formConfig: {
                schemas: searchFormSchema,
                fieldMapToNumber: [
                ],
                fieldMapToTime: [
                ],
            },
           actionColumn: {
               width: 120,
               fixed:'right'
           },
           beforeFetch: (params) => {
             return Object.assign(params, queryParam);
           },
           pagination:{
               current: 1,
               pageSize: 5,
               pageSizeOptions: ['5', '10', '20'],
           },
          // 显示底部合计
          showSummary: true,
          // 底部合计计算方法
          summaryFunc: onSummary,
        },
        exportConfig: {
            name:"销售合同",
            url: getExportUrl,
            params: queryParam,
        },
        importConfig: {
            url: getImportUrl,
            success: handleSuccess
        },

    })
  const userStore = useUserStore();
  const [registerTable, {reload},{ rowSelection, selectedRowKeys, }] = tableContext

  const mainId = computed(() => (unref(selectedRowKeys).length > 0 ? unref(selectedRowKeys)[0] : ''));
  //下发 mainId,子组件接收
  provide('mainId', mainId);
  const recordDatas = ref([]);
  // recordData.value.
  const selectedRows = computed(() => (unref(recordDatas).length > 0 ? unref(recordDatas)[0] : ref([])));
  provide('recordData', selectedRows);
    // 高级查询配置
    const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
  // 当选择的行变化时触发的事件
  function clickThenCheck(record, index, event) {
    // console.log("record===",record.id)
    // recordDatas.value=[];
    // recordDatas.value.push(record);
  }
  // 当选择的行变化时触发的事件
  function changeThenCheck(event) {
    try {
      console.log("event===",event.rows[0].id)
      recordDatas.value=[];
      recordDatas.value.push(event.rows[0]);
    }catch (error) {

    }

    // recordDatas.value.push(record);
  }

   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
  /**
   * 副总经理审批事件openViceGeneralManagerModal
   * openModal(true, {
   *        isUpdate: false,
   *        showFooter: true,
   *      });
   */
  function handleViceGeneralManager(record: Recordable) {
    console.log("openViceGeneralManagerModal==========",record)
    openViceGeneralManagerModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 总经理审批事件openGeneralManagerModal
   * openModal(true, {
   *        isUpdate: false,
   *        showFooter: true,
   *      });
   */
  function handleGeneralManager(record: Recordable) {
    console.log("openGeneralManagerModal==========",record)
    openGeneralManagerModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value},handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         // {
         //   label: '编辑',
         //   onClick: handleEdit.bind(null, record),
         //   auth: 'xcbd:xcbd_sales_contract:edit'
         // }
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         },
       ]
   }


  /**
   * 下拉操作栏
   */
  function getDropDownAction(record){
    if(record.processInitiator=='林泽鑫' && hasPermission('xcbd:generalManager')){
      return [
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
          auth: 'xcbd:xcbd_sales_contract:edit'
        },
        {
          label: '总经理审批',
          onClick: handleGeneralManager.bind(null, record),
        },
      ]
    } else if(record.processInitiator=='全忠' && hasPermission('xcbd:viceGeneralManager')){
      return [
        {
          label: '删除',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleDelete.bind(null, record),
            placement: 'topLeft',
          },
          auth: 'xcbd:xcbd_sales_contract:delete',
        },
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
          auth: 'xcbd:xcbd_sales_contract:edit',
        },
        {
          label: '副总经理审批',
          onClick: handleViceGeneralManager.bind(null, record),
        },
      ]
    }
    /*return [
      // {
      //   label: '详情',
      //   onClick: handleDetail.bind(null, record),
      // },
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'xcbd:xcbd_sales_contract:edit'
      },
      {
        label: '副总经理审批',
        onClick: handleViceGeneralManager.bind(null, record),
      },
      {
        label: '总经理审批',
        onClick: handleGeneralManager.bind(null, record),
      },
      /!*{
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft'
        },
        auth: 'xcbd:xcbd_sales_contract:delete'
      }*!/
    ]*/
  }
  function onSummary(tableData: Recordable[]) {
    // 可用工具方法自动计算合计
    const totals = mapTableTotalSummary(tableData, ['contractAmount', 'collectionAmount']);
    let contractAmount = totals.contractAmount;
    let collectionAmount = totals.collectionAmount;
    totals.collectionAmount='待'+collectionAmount+' 已'+(contractAmount-collectionAmount);
    console.log(collectionAmount)
    return [
      totals,
    ];
  }
</script>

<style lang="less" scoped>
  html[data-theme='light'] {
    .cgformErpList {
      height: 100%;
      .content {
        background-color: #fff;
        height: 100%;
      }
    }
  }
  
  :deep(.ant-picker),:deep(.ant-input-number){
    width: 100%;
  }
</style>
